package com.wz.leetcode.backtrack;

import java.util.ArrayList;
import java.util.List;

public class GenerateParentheses_22 {
    public static List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        dfs(new StringBuilder(), n, n, res);
        return res;
    }

    private static void dfs(StringBuilder builder, int left, int right, List<String> res) {
        if (left == 0 && right == 0) {
            res.add(builder.toString());
            return;
        }
        // 左括号剩下的更多，不对
        if (left > right) {
            return;
        }
        if (left > 0) {
            dfs(builder.append("("), left - 1, right, res);
            builder.deleteCharAt(builder.length() - 1);
        }
        if (right > 0) {
            dfs(builder.append(")"), left, right - 1, res);
            builder.deleteCharAt(builder.length() - 1);
        }
    }                                                                                                                                                                                                            

    public static void main(String[] args) {
        System.out.println(generateParenthesis(1));
        System.out.println(generateParenthesis(2));
        System.out.println(generateParenthesis(3));
    }
}
